package com.czy.owner.ui.message;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.GroupDetailsAdapter;
import com.czy.owner.entity.MessageContacts;
import com.czy.owner.global.Constants;
import com.czy.owner.db.UserHelper;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.disk.DiskLruCacheHelper;
import com.czy.owner.widget.RoundImageView;
import com.czy.owner.widget.SwitchView;
import com.easemob.cases.MessageHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.widget.EaseAlertDialog;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;

/**
 * Created by King on 2016/10/27 0027.
 */
public class GroupDetailsActivity extends BaseActivity implements View.OnClickListener{
    @BindView(R.id.btn_page_title_left)
    Button ivTitleBack;
    @BindView(R.id.tv_page_title_center)
    TextView tvTitleCenter;

    @BindView(R.id.iv_group_avatar)
    RoundImageView ivAvatar;
    @BindView(R.id.tv_group_name)
    TextView tvName;
    @BindView(R.id.tv_group_members_count)
    TextView tvMembersCount;
    @BindView(R.id.rv_group_members)
    RecyclerView rvMembers;
    @BindView(R.id.sv_block_message)
    SwitchView svBlockMessage;
    @BindView(R.id.ll_group_history)
    LinearLayout llHistory;
    @BindView(R.id.btn_exit)
    Button btnDelete;

    private String groupId;
    private EMGroup group;
    private GroupDetailsAdapter mAdapter;
    private DiskLruCacheHelper cacheHelper = null;
    private List<MessageContacts> mContactsList;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_group_details;
    }

    @Override
    protected void initInjector() {
        
    }

    @Override
    protected void initViews() {
        groupId = getIntent().getStringExtra("groupId");
        group = EMClient.getInstance().groupManager().getGroup(groupId);
        // we are not supposed to show the group if we don't find the group
        if(group == null){
            finish();
            return;
        }
        try {
            cacheHelper = new DiskLruCacheHelper(GroupDetailsActivity.this);
        } catch (IOException e) {
            e.printStackTrace();
        }
        initView();
        initListener();
        initContactList();
    }

    @Override
    protected void updateViews() {

    }


    private void initView(){
        if(TextUtils.isEmpty(group.getGroupName())){
            tvTitleCenter.setText("未命名");
        }else{
            tvTitleCenter.setText(group.getGroupName());
        }
        EaseUser user = MessageHelper.getInstance().getUserInfo(group.getOwner());
        if (user == null) {
            tvName .setText("群主：" + group.getOwner());
        } else {
            tvName .setText("群主：" + user.getNick());
        }
        tvMembersCount.setText("" + group.getMembers().size());
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvMembers.setLayoutManager(layoutManager);
        mAdapter = new GroupDetailsAdapter(this,group.getMembers(), GroupDetailsAdapter.SHOW_TYPE_DETAILS,group.getOwner());
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<String>() {
            @Override
            public void onItemClick(int position, String o, View view) {
                if (EMClient.getInstance().getCurrentUser().equals(o)) {
                    Toast.makeText(GroupDetailsActivity.this, "无法查看自己!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mContactsList == null || mContactsList.size() == 0) {
                    Toast.makeText(GroupDetailsActivity.this, "无法获取该联系人信息,请稍候重试!", Toast.LENGTH_SHORT).show();
                    return;
                }
                for (MessageContacts messageContacts : mContactsList) {
                    if (messageContacts.getImKey().equals(o)) {
                        Intent intent = new Intent(GroupDetailsActivity.this, ContactsPanelActivity.class);
                        intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, messageContacts);
                        startActivity(intent);
                        return;
                    }
                }

                Toast.makeText(GroupDetailsActivity.this, "无法获取该联系人信息!", Toast.LENGTH_SHORT).show();
            }
        });
        rvMembers.setAdapter(mAdapter);

        if(MessageHelper.getInstance().getIsNotDisturb(UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_IS_NOTICE_GROUP + groupId) == 1){
            svBlockMessage.setState(true);
        }else{
            svBlockMessage.setState(false);
        }
    }

    private void initListener() {
        ivTitleBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        svBlockMessage.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
            @Override
            public void toggleToOn() {
                /*try {
                    EMClient.getInstance().groupManager().blockGroupMessage(groupId);
                    svBlockMessage.toggleSwitch(true);
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    Toast.makeText(GroupDetailsActivity.this, "群屏蔽失败，请检查网络或稍后重试!", Toast.LENGTH_SHORT).show();
                    svBlockMessage.toggleSwitch(false);
                }*/
                svBlockMessage.toggleSwitch(true);
                MessageHelper.getInstance().setIsNotDisturb(UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_IS_NOTICE_GROUP + groupId, 1);
            }

            @Override
            public void toggleToOff() {
                /*try {
                    EMClient.getInstance().groupManager().unblockGroupMessage(groupId);
                    svBlockMessage.toggleSwitch(false);
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    Toast.makeText(GroupDetailsActivity.this, "解除群屏蔽失败，请检查网络或稍后重试!", Toast.LENGTH_SHORT).show();
                    svBlockMessage.toggleSwitch(true);
                }*/
                svBlockMessage.toggleSwitch(false);
                MessageHelper.getInstance().setIsNotDisturb(UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_IS_NOTICE_GROUP + groupId, 0);
            }
        });
        llHistory.setOnClickListener(this);
        btnDelete.setOnClickListener(this);
    }


    private void initContactList(){
        String dataSrc = null;
        if (cacheHelper != null) {
            dataSrc = cacheHelper.getAsString(UserHelper.getInstance().getUserAccount() + "_contacts");
        }
        if (TextUtils.isEmpty(dataSrc)) {
            RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_ADDRESS_BOOK);
            params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(GroupDetailsActivity.this).getSession());
            params.addBodyParameter("storeId", SharedPreferencesUtils.getParam(GroupDetailsActivity.this,UserHelper.getInstance().getUserAccount()+ Constants.SHARED_PREFERENCES_KEY_BINDSTOREID,0)+"");
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    String data = PhoneUtils.checkResponseFlag(GroupDetailsActivity.this, result);
                    if (data != null) {
                        if (cacheHelper != null) {
                            cacheHelper.put(UserHelper.getInstance().getUserAccount() + "_contacts", data);
                        }
                        mContactsList = new Gson().fromJson(data, new TypeToken<List<MessageContacts>>() {
                        }.getType());
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        } else {
            mContactsList = new Gson().fromJson(dataSrc, new TypeToken<List<MessageContacts>>() {
            }.getType());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_group_history:
                // 聊天记录
                Intent intent = new Intent(this, ChatHistoryActivity.class);
                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, groupId);
                startActivity(intent);
                break;
            case R.id.btn_exit:
                new EaseAlertDialog(GroupDetailsActivity.this, null, "退出后，将不再接收此群聊信息,是否确定退出？", null, new EaseAlertDialog.AlertDialogUser() {

                    @Override
                    public void onResult(boolean confirmed, Bundle bundle) {
                        if(confirmed){
                            try {
                                EMClient.getInstance().groupManager().leaveGroup(groupId);
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        setResult(RESULT_OK);
                                        finish();
                                        if(ChatActivity.activityInstance != null) {
                                            ChatActivity.activityInstance.finish();
                                        }
                                    }
                                });
                            } catch (final Exception e) {
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        PhoneUtils.ShowToastMessage(GroupDetailsActivity.this, getString(R.string.Exit_the_group_chat_failure));
                                    }
                                });
                            }
                        }
                    }
                }, true).show();
                break;

        }

    }
}
